<template>
  <!-- 添加或修改项目基础信息管理对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="100%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <div class="app-container" style="display: flex;">
      <div>
        <el-card class="box-card">
          <el-form :model="form" ref="form" size="small" :rules="rules" v-show="showSearch">
            <el-form-item label="采购类别:">
              <el-radio-group v-model="form.goodsType" @change="changeGoodsType">>
                <el-radio
                  v-for="dict in dict.type.goods_type"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="采购类型" prop="ywType">
              <el-select v-model="form.ywType" placeholder="请选择采购类型" clearable style="width: 180px;">
                <el-option v-for="dict in dict.type.caigou_type"
                           :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="定金:" prop="dingjin">
              <el-input-number v-model="form.dingjin" :precision="2" :min="0" style="width: 200px;"></el-input-number>
            </el-form-item>

            <el-form-item label="运费:" prop="shippingFee">
              <el-input-number v-model="form.shippingFee" :precision="2" :min="0"
                               style="width: 200px;"></el-input-number>
            </el-form-item>

            <el-form-item label="运费合并付款:" prop="depositMerge" v-if="form.shippingFee>0">
              <el-radio-group v-model="form.depositMerge">
                <el-radio v-for="dict in dict.type.yes_no"
                          :key="dict.value" :label="dict.value">{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="采购日期:" prop="ddDate">
              <el-date-picker clearable
                              v-model="form.ddDate"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择采购日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="供应商:" prop="supplierId">
              <el-select v-model="form.supplierId" placeholder="请选择供应商" filterable @change="selectSupplier"
                         style="width: 260px">
                <el-option v-for="dict in dict.type.goods_supplier" ref="myselectSsupplier"
                           :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="开户行:" prop="bankName">
              <el-input v-model="form.bankName" style="width: 190px;"></el-input>
            </el-form-item>
            <el-form-item label="银行行号:" prop="bankNo">
              <el-input v-model="form.bankNo" style="width: 170px;"></el-input>
            </el-form-item>
            <el-form-item label="银行账号:" prop="accountNo">
              <el-input v-model="form.accountNo" style="width: 170px;"></el-input>
            </el-form-item>
            <el-form-item label="备注:">
              <el-input v-model="form.remark" style="width: 210px;"></el-input>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
      <div style="width: 85%;padding: 0 10px;">
        <el-card class="box-card">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                   label-width="98px">
            <el-form-item label="请购单号" prop="nos">
              <el-input v-model="queryParams.nos" size="mini" placeholder="请输入订单编号" clearable
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="下单日期">
              <el-date-picker v-model="dateRange"
                              style="display: flex;"
                              value-format="yyyy-MM-dd"
                              type="daterange"
                              range-separator="-"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="订单编号" prop="projectNo">
              <el-input v-model="queryParams.projectNo" size="mini" placeholder="请输入订单编号" clearable
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="产品编码" prop="goodsCode">
              <el-input v-model="queryParams.goodsCode" size="mini" placeholder="请输入商品编码" clearable
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="产品名称" prop="goodsName">
              <el-input v-model="queryParams.goodsName" size="mini" placeholder="请输入商品名称" clearable
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="产品型号" prop="goodModel">
              <el-input v-model="queryParams.goodModel" size="mini" placeholder="请输入商品型号" clearable
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="业务员" prop="salesmanName">
              <el-input v-model="queryParams.salesmanName" size="mini" placeholder="请输入业务员" clearable
                        @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              <el-button type="primary" size="mini" icon="el-icon-plus" @click="submitForm">添 加</el-button>
              <el-button type="primary" size="mini" icon="el-icon-plus" @click="importForm">导 入 成 品</el-button>
              <el-button type="primary" size="mini" icon="el-icon-plus" @click="importCailiaoForm">导 入 材 料
              </el-button>
              <el-button type="danger" size="mini" icon="el-icon-s-open" @click="oneKeyZero">一 键 清 零</el-button>
              <el-button type="warning" size="mini" icon="el-icon-shopping-cart-1" @click="oneKeyBuy">一 键 采 购
              </el-button>
            </el-form-item>
          </el-form>
          <div v-if="dataList.length > 0">
            <div>已勾选订单数量合计: {{ dataList.reduce((acc, row) => acc + row.buyCount, 0) }}</div>
          </div>
          <el-table border v-loading="loading" :data="columns" @selection-change="handleSelectionChange"
                    show-summary :summary-method="getSummariesPlease" :max-height="500">
            <el-table-column type="selection" width="60" align="center" fixed="left"/>
            <el-table-column label="序号" type="index" width="50" align="center"/>
            <el-table-column label="请购单号" align="center" prop="nos"/>
            <el-table-column label="订单单号" align="center" prop="projectNo"/>
            <el-table-column label="产品编码" align="center" prop="goodsCode"/>
            <el-table-column label="产品名称" align="center" prop="goodsName"/>
            <el-table-column label="产品型号" align="center" prop="goodModel"/>
            <el-table-column label="产品类型" align="center" prop="type" />
            <el-table-column label="下单日期" align="center" prop="ddDate" width="100">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.ddDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="需求日期" align="center" prop="saleDate"/>
            <el-table-column label="业务员" align="center" prop="salesmanName"/>
            <el-table-column label="工程名称" align="center" prop="gongchengName" show-overflow-tooltip/>
            <el-table-column label="客户名称" align="center" prop="customerName" show-overflow-tooltip/>

            <el-table-column label="备注" align="center" prop="remark" width="120" fixed="right">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remark" size="mini"></el-input>
              </template>
            </el-table-column>

            <el-table-column label="成品/材料" align="center" prop="goodsType" fixed="right" width="100">
              <template slot-scope="scope">
                <el-select v-model="scope.row.addGoodsType" placeholder="请选择" size="mini">
                  <el-option label="成品" value="0"></el-option>
                  <el-option label="材料" value="1"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="请购数量" align="center" prop="pleaseBuyCount" fixed="right"/>
            <el-table-column label="采购剩余" align="center" prop="buyRemain" fixed="right"/>
            <el-table-column label="采购数量" align="center" prop="buyCount" width="160" fixed="right">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.buyCount" size="mini" :max="scope.row.buyRemain"></el-input-number>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize" @pagination="getList"/>
        </el-card>
      </div>
    </div>
    <el-card class="box-card">
      <el-table :data="columns2" ref="dragTable" row-key="id" v-loading="loading2" show-summary
                :summary-method="getSummaries">
        <el-table-column align="center" label="序号" type="index" width="50">
          <template slot-scope="scope">
            <span>{{ (queryParams2.pageNum - 1) * queryParams2.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column label="是否变更" align="center" key="changeStatus">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.changeStatus"
              active-value="1"
              inactive-value="0"
              @change="handleGoodsTypeChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="请购单号" align="center" prop="nos"/>
        <el-table-column label="产品选择" align="center" prop="goodsCode">
          <template slot-scope="scope">
            <el-autocomplete v-if="scope.row.changeStatus==='1'" style="width: 280px;"
                             v-model="scope.row.code"
                             :fetch-suggestions="querySearch"
                             placeholder="请输入内容">
              <template #default="{ item, index }">
                <div @click="handleClick(item, scope.$index,scope.row)">
                  {{ item.value }}
                </div>
              </template>
            </el-autocomplete>
            <span v-if="scope.row.changeStatus==='0'">产品选择</span>
          </template>
        </el-table-column>

        <el-table-column label="产品编码" align="center" prop="goodsCode"/>
        <el-table-column label="产品名称" align="center" prop="goodsName"/>
        <el-table-column label="成品/材料" align="center" key="status">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.goodsType"
              active-value="1"
              inactive-value="0"
              @change="handleGoodsTypeChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>


        <el-table-column label="产品型号" align="center" prop="goodModel"/>
        <el-table-column label="产品类型" align="center" prop="type" />
        <el-table-column label="需求日期" align="center" prop="deliveryTime"/>
        <el-table-column label="单价" width="160" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.goodsBuyPrice" @change="updateTotalCost(scope.row)" size="mini"
                             :min="0"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="采购数量" width="160" prop="shengyu" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.shengyu" @change="updateTotalCost(scope.row)" size="mini"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="重量" width="160" prop="dun" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.dun" size="mini"
                             @change="updateTotalCost(scope.row)"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="总价" width="160" prop="goodsBuyTotal" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.goodsBuyTotal" size="mini"
                             @change="updateBuyPriceByTotal(scope.row)"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark"/>
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="140">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="showChild(scope.row)">采购明细</el-button>
            <el-popconfirm :title="`确认删除 `+scope.row.goodsName+` 数据项？`" @confirm="handleDelete(scope.row)"
                           style="margin-left: 10px;">
              <el-button icon="el-icon-delete" size="mini" slot="reference" type="text"
                         v-hasPermi="['develop:ProjectBaseInfo:remove']">删除
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitCgd">提交采购单</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
    <upload-dialog ref="uploadDialog" @ok="getList" @handleFileSuccess="handleFileSuccess"></upload-dialog>
    <upload-dialog ref="uploadDialogCailiao" @ok="getList"
                   @handleFileSuccess="handleFileSuccessCailiao"></upload-dialog>
    <goods-salebuyLists ref="showForm" @ok="getList"></goods-salebuyLists>
  </el-dialog>
</template>

<script>
import {addAction, accMul, deleteAction, getAction, getById, updateAction, accAdd, accDiv} from '@/api/manage';
import {list} from "@/api/develop/goodsSaledo";
import GoodsSalebuyLists from "@/views/develop/lvBuy/module/GoodsSalebuyLists";
import UploadDialog from "@/views/upload/UploadDialog";
import {changeUserStatus} from "@/api/system/user";
import {parseTime} from "@/utils/common";

export default {
  name: "LvBuyAddFormList",
  dicts: ['goods_customer', 'company', 'yes_no', 'goods_supplier', 'goods_type', 'caigou_type', 'yes_no'],
  components: {
    GoodsSalebuyLists,
    UploadDialog
  },
  data() {
    return {
      proId: '',
      // 遮罩层
      title: "产品选择",
      loading: false,
      open: false,
      // 选中数组
      ids: [],
      proStatus: "",
      saleType: "2",
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库信息管理表格数据
      dataList: [],
      columns: [],
      dateRange: [],
      goodsList: [],
      form: {
        supplierId: null,
        supplierName: null,
        dingjin: null,
        kaihuhang: null,
        ddDate: null,
        zhanghao: null,
        hanghao: null,
        remark: null,
        ywType: null,
        depositMerge: null,
        goodsType: "0",
      },
      rules: {
        supplierId: [
          {required: true, message: "请选择供应商", trigger: "blur"}
        ],
        bankName: [
          {required: true, message: "请输入开户行", trigger: "blur"}
        ],
        /*bankNo: [
          {required: true, message: "请输入银行行号", trigger: "blur"}
        ],*/
        accountNo: [
          {required: true, message: "请输入银行账号", trigger: "blur"}
        ],
        ywType: [
          {required: true, message: "请选择采购类型", trigger: "blur"}
        ],
        depositMerge: [
          {required: true, message: "请选择运费是否合并付款", trigger: "blur"}
        ],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        model: null,
        costPrice: null,
        count: null,
        validityTerm: null,
        supplierId: null,
        supplierName: null,
        //  goodsType: "0",
        //   status: "4",
        isdo: "0",
        isBuy: "1",
        projectNo: null,
        projectName: null,
        goodsCode: null,
        goodsName: null,
        goodModel: null,
        salesmanName: null,
        nos: null,
        params: {
          dataFlag: "1"
        }
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 1000,
        id: null,
        name: null,
        model: null,
        brand: null,
        taxNo: null,
        addr: null,
        tel: null,
        bankName: null,
        bankNo: null,
        info: null,
        status: "5",
        isdo: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        type: null,
        orderByColumn: "a.create_time",
        isAsc: "asc",
      },
      total2: '',
      loading2: '',
      columns2: [],
      url: {
        listBuyRemainNotZero: '/goodsSaledo/goodsSaledo/listBuyRemainNotZero',
        goodsSupplierById: '/goodsSupplier/goodsSupplier/',
        remove: '/goodsOrderIn/goodsOrderIn/',
        export: '/goodsOrderIn/goodsOrderIn/export',
        insertForCg: '/goodsSalebuy/goodsSalebuy/insertForCg',
        submitCgd: '/goodsSalebuyall/goodsSalebuyall/submitCgd',
        list2: '/goodsSalebuyall/goodsSalebuyall/list',
        remove2: '/goodsSalebuyall/goodsSalebuyall/deleteCg/',
        submitProject: '/projectBaseInfo/projectBaseInfo/submitProject',
        submitGoodsbuyall: '/goodsSalebuyall/goodsSalebuyall/edit',
      },
      tableMaxHeight: window.innerHeight - 900,
    };
  },
  created() {

  },
  methods: {
    reset() {
      this.form = {
        id: null,
        supplierId: null,
        supplierName: null,
        dingjin: null,
        shippingFee: null,
        ddDate: null,
        bankName: null,
        bankNo: null,
        accountNo: null,
        remark: null,
        goodsType: "0",
      };
      this.resetForm("form");
    },
    dingjinValidator(rule, value, callback) {
      if (value === 0) {
        callback(new Error('定金不能为0'));
      } else {
        callback();
      }
    },
    selectSupplier(value) {
      let that = this;
      that.$nextTick(() => {
        let arr = that.$refs.myselectSsupplier;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].currentValue == value) {
            that.form.supplierName = arr[i].label;
            getById(this.url.goodsSupplierById, value).then(response => {
              that.form.bankName = response.data.bankName;//开户行
              that.form.accountNo = response.data.accountNo;//账号
              that.form.bankNo = response.data.bankNo;//行号
              //that.form.supplierId = response.data.id;//id
            });
          }
        }
      })
    },
    showChild(row) {
      this.$refs.showForm.showsalebuyList(row);
    },
    getList2() {
      let that = this;
      this.loading2 = true;
      this.queryParams2.createBy=this.$store.getters.name;
      getAction(this.url.list2, this.queryParams2).then(response => {
        that.columns2 = response.rows;
        that.total2 = response.total;
        that.loading2 = false;
        for (let i = 0; i < that.columns2.length; i++) {
          if (that.columns2[i].goodsType === "0") {
            if (that.columns2[i].goodsBuyPrice === 0) {
              that.columns2[i].goodsBuyTotal = accMul(that.columns2[i].shengyu, that.columns2[i].goodsUnitPrice);
            } else {
              that.columns2[i].goodsBuyTotal = accMul(that.columns2[i].shengyu, that.columns2[i].goodsBuyPrice);
            }
          }
          if (that.columns2[i].goodsType === "1") {
            if (that.columns2[i].goodsBuyPrice === 0) {
              that.columns2[i].goodsBuyTotal = accMul(that.columns2[i].dun, that.columns2[i].goodsUnitPrice);
            } else {
              that.columns2[i].goodsBuyTotal = accMul(that.columns2[i].dun, that.columns2[i].goodsBuyPrice);
            }
          }
        }
      });
    },
    handleUpdate(row) {
      const id = row.id || this.ids;
      this.proId = id;
      this.open = true;
      this.loading = false;
      this.proStatus = row.status;
      // this.chose(this.proId, "2");
      this.getList2();

    },
    refreshPageData() {
      let that = this;
      let param = {
        id: that.proId
      }
      that.handleUpdate(param);

    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.remove2, ids).then(response => {
        this.refreshPageData();
        this.$modal.msgSuccess("删除成功");
        this.handleQuery();
      }).catch(() => {
      });
    },
    updateTotalCost(row) {

      let that = this;
      if (row.goodsType === "0") {
        if (row.shengyu && row.goodsBuyPrice) {
          let totleCost = accMul(row.shengyu, row.goodsBuyPrice);
          that.$set(row, "goodsBuyTotal", totleCost);
        }
      }
      if (row.goodsType === "1") {
        if (row.dun && row.goodsBuyPrice) {
          let totleCost = accMul(row.dun, row.goodsBuyPrice);
          that.$set(row, "goodsBuyTotal", totleCost);
        }
      }
      this.updateGoodsBuyAll(row);
    },

    updateBuyPriceByTotal(row) {
      let that = this;
      if (row.goodsType === "0") {
        if (row.shengyu && row.goodsBuyTotal) {
          let totalCost = accDiv(row.goodsBuyTotal, row.shengyu);
          that.$set(row, "goodsBuyPrice", totalCost);
        }
      }
      if (row.goodsType === "1") {
        if (row.goodsBuyTotal) {
          let dun = accDiv(row.goodsBuyTotal, row.goodsBuyPrice);
          that.$set(row, "dun", dun);
        }
      }
    },

    updateGoodsBuyAll(row) {
      updateAction(this.url.submitGoodsbuyall, row).then(response => {
      })
    },

    handleAddCg() {
      this.open = true;
      this.reset();
      this.getList2();
      this.form.ddDate = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
    },
    getList() {
      this.loading = true;
      this.addDateRange(this.queryParams, this.dateRange);
      getAction(this.url.listBuyRemainNotZero, this.queryParams).then(response => {
        let res = response.rows;
        this.columns = res;
        for (let i = 0; i < this.columns.length; i++) {
          this.columns[i].addGoodsType = this.form.goodsType;
          this.columns[i].buyCount = 0;
        }
        this.total = response.total;
        this.loading = false;
      });

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      // this.reset();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.dataList = selection;
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    submitCgd() {
      let that = this;
      let arrays = that.columns2;
      for (let i = 0; i < arrays.length; i++) {
        if (arrays[i].goodsBuyPrice === 0) {
          that.$modal.msgError(arrays[i].goodsName + ":产品单价不能为0");
          return;
        }
      }
      that.$refs["form"].validate(valid => {
        if (valid) {
          const goodsSaledo = Object.assign({});
          goodsSaledo.supplierId = that.form.supplierId;
          goodsSaledo.supplierName = that.form.supplierName;
          goodsSaledo.bankName = that.form.bankName;
          goodsSaledo.accountNo = that.form.accountNo;
          goodsSaledo.bankNo = that.form.bankNo;
          goodsSaledo.goodsType = that.form.goodsType;
          goodsSaledo.ywType = that.form.ywType;
          goodsSaledo.dingjin = that.form.dingjin;
          goodsSaledo.shippingFee = that.form.shippingFee;
          goodsSaledo.remark = that.form.remark;
          goodsSaledo.ddDate = that.form.ddDate;
          goodsSaledo.depositMerge = that.form.depositMerge;
          goodsSaledo.columns = that.columns2;
          addAction(this.url.submitCgd, goodsSaledo).then(response => {
            this.refreshPageData();
            this.$modal.msgSuccess("提交成功!");
            this.open = false;
            that.$emit('ok');
            this.handleQuery();
          }).catch(() => {
          });
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      let that = this;
      const ids = this.ids;
      if (ids == null || ids == '' || ids == 'undefined') {
        that.$modal.msgError("请选择一条记录");
      } else {
        let sum = 0;
        that.dataList.forEach(function (number) {
          if (number.addGoodsType == null) {
            sum += 1
          }
        });
        if (sum > 0) {
          that.$modal.msgError("请选择产品类型！");
          return;
        }

        for (let i = 0; i < that.dataList.length; i++) {
          if (that.dataList[i].buyCount === 0) {
            that.$modal.msgError("采购数量不能为0");
            return;
          }
        }

        const goodsSaledo = Object.assign({});
        goodsSaledo.columns = that.dataList;
        addAction(that.url.insertForCg, goodsSaledo).then(response => {
          that.$modal.msgSuccess("添加成功");
          that.$emit('ok');
          that.getList2();
          that.handleQuery();
        });
      }
    },

    importForm() {
      this.$refs.uploadDialog.title = "采购产品信息导入";
      this.$refs.uploadDialog.tmplName = "采购产品信息导入模板.xlsx";
      this.$refs.uploadDialog.fileName = "采购产品信息导入模板.xlsx";
      this.$refs.uploadDialog.uploadUrl = "/goodsSaledo/goodsSaledo/importCaigouData";
      this.$refs.uploadDialog.show();
    },
    handleFileSuccess(response, file, fileList) {
      this.$refs.uploadDialog.open = false;
      this.$refs.uploadDialog.isUploading = false;
      if (response.data.code == "200") {
        this.$alert("导入数据：" + response.data.num + "条！更新数据：" + response.data.numupdate + "条！" + response.data
          .errorText, "导入结果", {
          dangerouslyUseHTMLString: true
        });
      } else {
        this.$alert("导入数据：" + response.data.num + "条！更新数据：" + response.data.numupdate + "条！" + response.data
          .errorText, "导入结果", {
          dangerouslyUseHTMLString: true
        });
      }
      this.getList();
    },

    importCailiaoForm() {
      this.$refs.uploadDialogCailiao.title = "采购材料信息导入";
      this.$refs.uploadDialogCailiao.tmplName = "采购材料信息导入模板.xlsx";
      this.$refs.uploadDialogCailiao.fileName = "采购材料信息导入模板.xlsx";
      this.$refs.uploadDialogCailiao.uploadUrl = "/goodsSaledo/goodsSaledo/importCaigouCailiao";
      this.$refs.uploadDialogCailiao.show();
    },

    handleFileSuccessCailiao(response, file, fileList) {
      this.$refs.uploadDialogCailiao.open = false;
      this.$refs.uploadDialogCailiao.isUploading = false;
      if (response.data.code == "200") {
        this.$alert("导入数据：" + response.data.num + "条！更新数据：" + response.data.numupdate + "条！" + response.data
          .errorText, "导入结果", {
          dangerouslyUseHTMLString: true
        });
      } else {
        this.$alert("导入数据：" + response.data.num + "条！更新数据：" + response.data.numupdate + "条！" + response.data
          .errorText, "导入结果", {
          dangerouslyUseHTMLString: true
        });
      }
      this.getList();
    },

    changeGoodsType() {
      this.getList();
    },

    handleGoodsTypeChange(row) {
      this.updateGoodsBuyAll(row);
    },

    getSummariesPlease(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if (column.property === "buyCount" || column.property === "pleaseBuyCount" || column.property === "buyRemain") {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },

    getSummaries(param) {
      // console.log(param);
      const {columns, data} = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if (column.property === "dun" || column.property === "shengyu" || column.property === "goodsBuyTotal") {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },

    /** 一键清零 */
    oneKeyZero() {
      this.columns.forEach((item, index) => {
        this.columns[index].buyCount = 0;
      });
    },
    /** 一键采购 */
    oneKeyBuy() {
      this.columns.forEach((item, index) => {
        this.columns[index].buyCount = this.columns[index].buyRemain;
      });
    },
    /** 查询物料 */
    querySearch(queryString, cb) {
      let that = this;
      let params = {model: queryString};
      getAction('/goodsOrderIn/goodsOrderIn/list', params).then(response => {
        that.goodsList = response.rows;
        for (let i = 0; i < this.goodsList.length; i++) {
          that.goodsList[i].value = that.goodsList[i].model + '-' + that.goodsList[i].code;
        }
        const goodsList = that.goodsList;
        const results = queryString
          ? goodsList.filter(that.createFilter(queryString))
          : goodsList;
        // 调用 callback 返回建议列表的数据
        cb(results);
      })
    },

    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().includes(queryString.toLowerCase())
        );
      };
    },

    handleClick(item, index, row) {
      // 如果 columns2 中已经存在该商品，则不能修改成这个产品
      let isExist = false;
      this.columns2.forEach((item2, index2) => {
        if (item2.goodsId == item.id) {
          isExist = true;
        }
      });
      if (isExist) {
        this.$message.error("该商品已存在，不能修改");
        return;
      }
      this.$nextTick(() => {
        row.goodsCode = item.code;
        row.goodsName = item.name;
        row.goodsId = item.id;
        row.goodModel = item.model;
        this.$set(this.columns2, index, row);
        this.updateGoodsBuyAll(row);
      })
    },


  }
};
</script>
